class User < ActiveRecord::Base
  attr_accessor :phone_cache
  attr_accessor :current_password
  attr_accessor :password_confirmation
  attr_accessor :login

  validates :phone, presence: false, length: {minimum: 11, maximum: 11}, allow_nil:true
  validates :email, presence: true, length: {maximum: 50}, uniqueness: true, format: /@/, allow_nil: true

  belongs_to :organization
  belongs_to :parent, class_name: 'User'
  belongs_to :society
  belongs_to :fellow
  belongs_to :major
  belongs_to :sub_college
  has_many :questions
  has_many :answers
  #角色
  has_many :user_roles, dependent: :delete_all
  has_many :roles, through: :user_roles
  has_many :permissions, through: :roles
  accepts_nested_attributes_for :user_roles

  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable and :omniauthable
  devise :database_authenticatable, :registerable, :lockable, :token_authenticatable,
         :recoverable, :rememberable, :trackable, :validatable, :authentication_keys => [:login]

  before_save :ensure_authentication_token
  # before_save :add_pinyin

  def phone_required?
    false
  end

  def add_pinyin
    pys = " #{PinYin.abbr(self.real_name)}"

    self.pinyin = (PinYin.of_string(self.real_name).join) << pys
  end

  def self.find_for_database_authentication(warden_conditions)
    conditions = warden_conditions.dup
    if login = conditions.delete(:login)
      where(conditions.to_h).where(['lower(phone) = :value OR lower(email) = :value', {:value => login.downcase}]).first
    else
      where(conditions.to_h).first
    end
  end

  def to_all_json
    user_json = self.as_json()
    user_json[:fellow_name] = self.fellow_id.present? ? self.fellow.name : '' if self.fellow
    # user_json[:major] = self.major_id.present? ? self.major.name : '' if self.major
    # user_json[:sub_college] = self.sub_college_id.present? ? self.sub_college.name : ''
    user_json
  end
end
